package com.idp.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.idp.common.enums.MessageEnum;
import com.idp.common.error.SystemException;
import com.idp.common.model.PageModel;
import com.idp.demo.dto.GoodsCategoryDto;
import com.idp.demo.dto.GoodsCategorySearchDto;
import com.idp.demo.entity.GoodsCategoryEntity;
import com.idp.demo.mapper.GoodsCategoryMapper;
import com.idp.demo.service.GoodsCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品类别Service实现类
 * @author King
 */
@Service("goodsCategoryService")
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

	@Autowired
	private GoodsCategoryMapper goodsCategoryMapper;

	@Override
	public PageModel<GoodsCategoryDto> findByPage(GoodsCategorySearchDto goodsCategorySearchDto) {

		PageModel<GoodsCategoryDto> page = new PageModel<GoodsCategoryDto>();

		page.setList(goodsCategoryMapper.getList(goodsCategorySearchDto));

		return page;
	}

	@Override
	public GoodsCategoryDto getById(String id) {

		if(ObjectUtil.isEmpty(id)) {
			throw new SystemException(MessageEnum.PARAM_ERROR);
		}

		GoodsCategoryDto goodsCategoryDto = goodsCategoryMapper.getById(id);

		if(goodsCategoryDto == null) {
			throw new SystemException(MessageEnum.DATA_NOT_EXIST);
		}

		return goodsCategoryDto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(GoodsCategoryDto goodsCategoryDto) {

		GoodsCategoryEntity goodsCategoryEntity = BeanUtil.toBean(goodsCategoryDto, GoodsCategoryEntity.class);

		goodsCategoryMapper.insert(goodsCategoryEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(GoodsCategoryDto goodsCategoryDto) {

		GoodsCategoryEntity goodsCategoryEntity = goodsCategoryMapper.selectById(goodsCategoryDto.getId());

        if(goodsCategoryEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }
		CopyOptions copyOptions = new CopyOptions();
		copyOptions.setIgnoreNullValue(true);
		BeanUtil.copyProperties(goodsCategoryDto, goodsCategoryEntity, copyOptions);

		goodsCategoryMapper.updateById(goodsCategoryEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(String id) {

		GoodsCategoryEntity goodsCategoryEntity = goodsCategoryMapper.selectById(id);

        if(goodsCategoryEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }

		goodsCategoryMapper.deleteById(id);
	}

	@Override
	public List<GoodsCategoryDto> findAll() {
		List<GoodsCategoryEntity> list = goodsCategoryMapper.selectList(null);
		return BeanUtil.copyToList(list, GoodsCategoryDto.class);
	}

}
